
var  showErrorMsg = false;

var header = {
  'Accept': 'application/json',
  'content-type': 'application/json',
  'Authorization': null,
}

function setResult(d) {
  return {
    code: d.code || 200,
    msg: d.msg || '获取数据成功！',
    data: d.data || [],
    error: d.error || null
  };
}

/**
 * request get请求
 */
function getReq(url,cb) {
  wx.showLoading({
    title: '加载中',
  });
  wx.request({
    url: url,
    method: 'GET',
    header: header,
    success: function (res) {
      wx.hideLoading();
      //var d = setResult(res);
      return typeof cb == "function" && cb(res);
    },
    fail: function (e) {
      wx.hideLoading();
      if (showErrorMsg){
        wx.showModal({
          title: '网络错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        });
      }
      // 封装错误信息
      var d = {};
      d.msg = '网络出错，请刷新重试';
      d.code = 500;
      d.error = e;
      var result = setResult(d);
      return typeof cb == "function" && cb(result);
    }
  })
}

/**
 * post请求
 */
function postReq(url, data, cb) {
  wx.showLoading({
    title: '加载中',
  });
  wx.request({
    url: url,
    header: header,
    data: data,
    method: 'post',
    success: function (res) {
      wx.hideLoading();
      var d = setResult(res);
      return typeof cb == "function" && cb(d);
    },
    fail: function () {
      wx.hideLoading();
      if (showErrorMsg) {
        wx.showModal({
          title: '网络错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        });
      }
      // 封装错误信息
      var d = {};
      d.msg = '网络出错，请刷新重试';
      d.code = 500;
      d.error = e;
      var result = setResult(d);
      return typeof cb == "function" && cb(result);
    }
  })
}

module.exports = {
  getReq: getReq,
  postReq: postReq,
  header: header,
}